import './index.scss';
import React, { Component } from 'react';
import axios from 'axios';
import Compressor from 'compressorjs';
import { loadingOn, loadingOff } from 'components/Loading';
import logoImg from 'images/logo-img.png';
import qs from 'qs';
import MemorizedState from 'hoc/MemorizedState';
import Notice from '../Notice';

@MemorizedState({ ignore: ['finished',  'shops', 'subItem']})
class Page extends Component {
	state = {
		shops: ''
	}

	componentDidUpdate() {
		this.props.memorize(this.state);
	}

	componentWillMount() {
		this.setState({
			...this.props.memory
		});
		document.title = '阿里健康疫苗预约核销确认登记';
		axios.get('https://appapi.jzdoctor.com/config/hospital.php').then(res => {
			this.setState({ shops: res.data });
		});
	}

	submit = () => {
		let { orderNo, name, mobile, cardNo, bookName, bookShop, payAmount, url, code } = this.state;

		if (!orderNo) return alert('请您输入订单号');
		if (!name) return alert('请您输入姓名');
		if (!mobile) return alert('请您输入手机号');
		if (!cardNo) return alert('请您输入身份证');
		if (!bookName) return alert('请您选择预约项目');
		if (!bookShop) return alert('请您选择下单预约门店');
		if (!payAmount) return alert('请您输入实付金额');
		if (!url && !code) return alert('请您上传电子核销码截图或输入核销码');

		if (this.requesting) return;
		this.requesting = true;

		let data = { ...this.state };
		delete data.preview;
		delete data.shops;
		data.channel = qs.parse(location.href.split('?')[1]).channel;

		axios.post(`${APP_CONFIG.appServer}/common/review/aliHealthVaccine/saveVerification`, data).then(res => {
			if (res.data.code == 0) {
				this.setState({
					finished: true
				});
				this.props.clearMemorized();
			}
			else {
				alert(res.data.msg);
				this.requesting = false;
			}
		}).finally(res => {
			this.requesting = false;
		});;
	}

	updateField = (fieldName, event) => {
		this.setState({ [fieldName]: typeof event ==='string' ? event : event.target.value });
	}

	handleUpload = (input) => {
		//  format check
		let files = input.target.files || input.dataTransfer.files;

		if (!files.length) return;

		let isValid = [].every.call(files, file => /\.jpe?g|png$/.test(file.name.toLowerCase()));

		if (!isValid) return alert('请选择图片');

		loadingOn();

		//  compress before preview & uploading
		new Compressor(files[0], {
			quality: 0.4,
			convertSize: 200000,
			maxWidth: 1000,
			maxHeight: 1000,
			success: (result) => {
				let reader = new FileReader();

				reader.onload = (e) => {
					let src = e.target.result;

					//  set preview
					this.setState({
						preview: src
					});

					//  uploading
					let bodyFormData = new FormData();
					bodyFormData.append('image', files[0]);

					axios.post(`${APP_CONFIG.appServer}/common/review/file/uploadImage`, bodyFormData, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					}).then(res => {
						loadingOff();

						if (res.data.code !== 0) {
							alert('上传照片失败, 请您重新上传');
							this.setState({
								preview: '',
								url: ''
							})
						}
						else {
							this.setState({
								url: res.data.data.url
							})
						}
					}).catch(e => {
						loadingOff();
					});
				};

				reader.onerror = (e) => {
					loadingOff();
				}

				reader.readAsDataURL(result);
			},
			error: () => {
				loadingOff();
			}
		});
	}

	render() {
		if (this.state.finished) return <h1 style={{padding: '20px', textAlign: 'center'}}>提交成功, 请关闭本页</h1>;

		return (
			<div className="misc-booking misc-booking-confirm-register">
				<div className="misc-booking-confirm-register-hd">
					<h1>阿里健康疫苗预约核销确认登记</h1>
					<p>【请详细准确填写资料】</p>
					<p>【若资料信息有误可能导致无法为您安排接种】</p>
					<img src={logoImg} alt="" style={{width: '100%', marginBottom: '10px'}}/>
				</div>

				<div className="misc-booking-confirm-register-bd">
					<div className="rules">
						※注意事项（请认真阅读）：<br/>
						1、该表格为确认预约核销登记表，不填写提交则默认放弃接种，将不予安排接种门诊；<br/>
						2、核销码提供核销后，作为确认预约安排凭证，只需在购买时约定的那个月底前等待预约接种医院致电联系，请根据您自身适合接种时间安排行程，与院方预约接种即可；<br/>
						3、核销码作为确认预约凭证，不核销不予安排接种，核销后在购买的月份月底前，院方会通知您安排时间进行疫苗接种；<br/>
						4、核销码在核销前后，若对本产品不满意，可随时联系退款；未接种或未享受产品配套服务时，均可全额退款，无需担心核销后不可退款； <br/>
						5、若已开始接种疫苗或已享受产品配套服务，则不可退款；<br/>
						6、有任何疑问，欢迎致电联系（021-62141588）；或进入阿里健康旗舰店咨询旺旺客服；<br/>
						7、更多资讯欢迎关注：官方微博：彩虹育儿 ； 官方微信公众号：彩虹育儿
					</div>
					<div className="form">
						<div className="form-row">
							<div className="form-label">
								<p>阿里健康订单号：</p>
							</div>
							<div className="form-item">
								<input type="text" className="input-text" onChange={this.updateField.bind(this, 'orderNo')} value={this.state.orderNo} />
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>接种人姓名：</p>
							</div>
							<div className="form-item">
								<input type="text" className="input-text" onChange={this.updateField.bind(this, 'name')} value={this.state.name} />
							</div>
						</div>
						<div className="form-row">
							<div className="form-label form-label-large">
								<p>接种人手机：</p>
							</div>
							<div className="form-item">
								<input type="tel" className="input-text input-text-large" onChange={this.updateField.bind(this, 'mobile')} value={this.state.mobile} placeholder="请输入接种人的11位手机号码" />
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>接种人身份证：</p>
							</div>
							<div className="form-item">
								<input type="text" className="input-text" onChange={this.updateField.bind(this, 'cardNo')} value={this.state.cardNo} />
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>预约项目：</p>
							</div>
							<div className="form-item radio-group">
								<p onClick={this.updateField.bind(this, 'bookName', '九价HPV疫苗')}><input type="radio" name="bookName" value="九价HPV疫苗" checked={this.state.bookName === '九价HPV疫苗'}/>九价HPV疫苗</p>
                <p onClick={this.updateField.bind(this, 'bookName', '二价HPV疫苗')}><input type="radio" name="bookName" value="二价HPV疫苗" checked={this.state.bookName === '二价HPV疫苗'}/>二价HPV疫苗</p>
								<p onClick={this.updateField.bind(this, 'bookName', '四价HPV疫苗')}><input type="radio" name="bookName" value="四价HPV疫苗" checked={this.state.bookName === '四价HPV疫苗'}/>四价HPV疫苗</p>
								<p onClick={this.updateField.bind(this, 'bookName', '23价肺炎疫苗')}><input type="radio" name="bookName" value="23价肺炎疫苗" checked={this.state.bookName === '23价肺炎疫苗'}/>23价肺炎疫苗</p>
								<p onClick={this.updateField.bind(this, 'bookName', '13价肺炎疫苗')}><input type="radio" name="bookName" value="13价肺炎疫苗" checked={this.state.bookName === '13价肺炎疫苗'}/>13价肺炎疫苗</p>
                <p onClick={this.updateField.bind(this, 'bookName', '成人三价流感疫苗')}><input type="radio" name="bookName" value="成人三价流感疫苗" checked={this.state.bookName === '成人三价流感疫苗'}/>成人三价流感疫苗</p>
                <p onClick={this.updateField.bind(this, 'bookName', '成人四价流感疫苗')}><input type="radio" name="bookName" value="成人四价流感疫苗" checked={this.state.bookName === '成人四价流感疫苗'}/>成人四价流感疫苗</p>
                <p onClick={this.updateField.bind(this, 'bookName', '儿童三价流感疫苗')}><input type="radio" name="bookName" value="儿童三价流感疫苗" checked={this.state.bookName === '儿童三价流感疫苗'}/>儿童三价流感疫苗</p>
								<p onClick={this.updateField.bind(this, 'bookName', '儿童疫苗')}><input type="radio" name="bookName" value="儿童疫苗" checked={this.state.bookName === '儿童疫苗'}/>儿童疫苗</p>
								<p onClick={this.updateField.bind(this, 'bookName', '健康体检')}><input type="radio" name="bookName" value="健康体检" checked={this.state.bookName === '健康体检'}/>健康体检</p>
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>电子核销码截图：</p>
								<small>（若无法截图上传，可截图订单后填写10位数核销码）</small>
							</div>
							<div className="form-item">
								<input
									type="file"
									accept="image/*"
									onChange={e => this.handleUpload(e)}
									onClick={e => (e.target.value = null)}
									className="uploadInput"
									placeholder="点击选择图片"
								/>
								<img src={this.state.preview} style={{width: '30%', display: 'block', marginTop: '20px'}} alt=""/>
							</div>
						</div>
						<div className="form-row">
							<div className="upload-tips">
								<p>(参考下方图示，若上传错误将导致无法预约成功)</p>
								<p>(如有疑问请及时拨打预约咨询热线反馈)</p>
								<p>示例：</p>
							</div>
							<img style={{width: '100%'}} src="http://pcdn.mikecrm.com/ugc_7_a/pub/vb/vb01tqys8mdstbr9a0zm207n12etk6st/form/image/Fvuk2MqMDiFz2PWmdhbqgIJmAnt5FdoG.jpg" />
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>电子凭证核销码：</p>
								<small>（无法截图上传时，选择手动输入填写，非必填）</small>
							</div>
							<div className="form-item">
								<input type="text" className="input-text" placeholder="（10位核销码，如：4627384234）" onChange={this.updateField.bind(this, 'code')} value={this.state.code} />
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>下单预约门店：</p>
								<small>（选择门店务必与阿里健康订单匹配）</small>
							</div>
							<div className="form-item">
								<select onChange={this.updateField.bind(this, 'bookShop')} value={this.state.bookShop}>
									{
										this.state.shops.split('\n').filter(i => i.trim()).map((item, index) => <option value={item.trim()} key={index}>{item.trim()}</option>)
									}
								</select>
							</div>
						</div>
						<div className="form-row">
							<div className="form-label">
								<p>实付金额：</p>
							</div>
							<div className="form-item">
								<input type="number" placeholder="去除所有优惠后真实支付金额" className="input-text" onChange={this.updateField.bind(this, 'payAmount')} value={this.state.payAmount} />
							</div>
						</div>
						<div className="form-row">
							<button className="button" onClick={this.submit}>提交</button>
						</div>
						<Notice></Notice>
					</div>
				</div>
			</div>
		);
	}
}

export default Page;